package com.wzm.service.impl;

import com.wzm.domain.Move;
import com.wzm.domain.User;
import com.wzm.domain.UserMove;
import com.wzm.feign.MoveClient;
import com.wzm.mapper.UserMapper;
import com.wzm.service.UserService;
import com.wzm.util.Ajaxresult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MoveClient moveClient;

    @Override
    public List<Move> findAll() {
        return moveClient.findAll();
    }

    @Override
    @Transactional
    public Ajaxresult buyById(UserMove userMove) {
        Move byId = moveClient.findById(userMove.getMovie_ticket_id());
        Ajaxresult res;
        if (byId == null) {
            return new Ajaxresult(false, "已售完", "请下次再来");
        } else {
            Integer price = byId.getPrice();
            Long id = userMove.getUser_id();
            User user = userMapper.findById(id);
            if ((user.getBalance() - price) < 0) {
                return new Ajaxresult(false, "余额不足", "请充值");
            }
            res = moveClient.buyById(userMove);
            if(res.getSuccess()){
                user.setId(id);
                user.setBalance(user.getBalance() - price);
                userMapper.updateBalance(user);
            }
            return res;
        }
    }

    @Override
    @Transactional
    public Ajaxresult addUser(User user) {
        User use = userMapper.findByUsername(user.getUsername());
        if(use!=null){
            return new Ajaxresult(false,"用户名重复","请重新输入");
        }
        Ajaxresult res = moveClient.sendTicket(user);
        if(res.getSuccess()){
            userMapper.addUser(user);
            return res;
        }
        return res;
    }

    @Override
    public Ajaxresult watch(Long id) {
        return moveClient.watch(id);
    }
}
